package denaris.midlet;

import java.util.Random;

import javax.microedition.lcdui.Graphics;

import denaris.core.AbstractDenarisMap;
import denaris.core.Scorebar;
import denaris.core.Statusbar;
import denaris.core.entity.Player;
import denaris.factory.DenarisMapFactory;
import denaris.midlet.DenarisGameCanvas.DisplayProperties;

/**
 * The GameScreen represents the most used part in Denaris. It provides the game
 * loop where the current entities and maps are permanently updated. The
 * GameScreen runs in its own thread.
 * 
 * @author stkl23
 * 
 */
public class GameScreen extends AbstractScreen {
	public static int SCROLL_SPEED = 1;

	public static Random RANDOM = new Random();

	private static GameScreen instance = null;

	private AbstractDenarisMap map;

	/** the current area... */
	private int currentArea;

	private Player player;
	
	private boolean initialized = false;

	protected GameScreen() {
	}

	/**
	 * Initialize the game screen
	 * 
	 */
	public void initialize() {
		if (!initialized) {
			// load the first map
			map = DenarisMapFactory.createMap("map1", 334, 13, DenarisMapFactory.DEFAULT_CELL_WIDTH, DenarisMapFactory.DEFAULT_CELL_HEIGHT);
			DenarisGameCanvas.getInstance().adjustGameHeightToMapHeight(map);
			
			player = new Player(map);
			map.setPlayerGroup(player);
			map.initialize();
			
			setCurrentArea(1);
			
			initialized = true;
		}
		doFullRepaintToBuffer(DenarisGameCanvas.getInstance().getBuffer());
	}


	public static int nextPositiveInt(int max) {
		int result = RANDOM.nextInt() % max;
		if (result < 0) {
			result *= -1;
		}
		return result;
	}

	public static GameScreen getInstance() {
		if (instance == null) {
			instance = new GameScreen();
		}
		return instance;
	}

	public AbstractDenarisMap getCurrentMap() {
		return map;
	}

	public int getCurrentArea() {
		return currentArea;
	}

	public void setCurrentArea(int currentArea) {
		this.currentArea = currentArea;
	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public AbstractDenarisMap getMap() {
		return map;
	}

	public void setMap(AbstractDenarisMap map) {
		this.map = map;
	}

	public void paintScreenToBuffer(Graphics g) {
		map.paint(g);
	}

	public void doFullRepaintToBuffer(Graphics g) {
		// clear buffer
		g.setClip(0, 0, DisplayProperties.DISPLAY_WIDTH, DisplayProperties.DISPLAY_HEIGHT);
		g.setColor(0);
		g.fillRect(0, 0, DisplayProperties.DISPLAY_WIDTH, DisplayProperties.DISPLAY_HEIGHT);
		// paint the statusbar (this doesn't need to be done every frame)
		Statusbar.getInstance().doFullRepaint(g);
		// draw scorebar
		Scorebar.getInstance().doFullRepaint(g);
		// draw map
		getMap().paint(g);
	}

	public void update() {
		// update the map
		map.update();
	}
}
